package com.runa.persistence.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import java.util.Optional;

@Slf4j
public class CommJpaRepository<T, ID> extends SimpleJpaRepository<T, ID> {

    private JpaEntityInformation<T, ID> jpaEntityInformation;

    public CommJpaRepository(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.jpaEntityInformation = entityInformation;
    }

    public CommJpaRepository(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
    }

//    public CommJpaRepository(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
//        super(entityInformation, entityManager);
//        this.jpaEntityInformation = entityInformation;
//    }
//
//    public CommJpaRepository(Class<T> domainClass, EntityManager em) {
//        super(domainClass, em);
//    }

//    @Autowired
//    public CommJpaRepository(JpaEntityInformation<T, ID>  jpaEntityInformation, EntityManager entityManager) {
//        super(jpaEntityInformation, entityManager);
//        this.jpaEntityInformation = jpaEntityInformation;
//    }

    @Override
    public <S extends T> S save(S entity) {
        ID id = (ID) jpaEntityInformation.getId(entity);
        if (id != null) {
            Optional<T> op = findById(id);
            if (op.isPresent()) {
                T t = op.get();
                BeanUtils.copyPropertiesWithoutNull(entity, t);
                entity = (S) t;
            }
        }
        return super.save(entity);
    }
}
